package com.yisu.expressway.ewf.common.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.IOException;
import java.util.Arrays;

/**
 * Created by nichole on 2016/10/4.
 */
public class QiNiuUploadUtil {

    public static String getUpToken(Uploader uploader){
        Auth auth = Auth.create(uploader.getAccessKey(), uploader.getSecretKey());
        return auth.uploadToken(uploader.getBucketName());
    }

    public static boolean upload(Uploader uploader) throws IOException {
        UploadManager uploadManager = new UploadManager();
        try {
            uploadManager.put(uploader.getData(), uploader.getFileName(), getUpToken(uploader));
            return true;
        } catch (QiniuException e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    public static String generateFileName() {
        return DateFormatUtils.format(System.currentTimeMillis(), "yyMMddHHmmssSS") + RandomUtils.nextLong(100000000l, 999999999l);
    }

    public static class Uploader {
        private String accessKey;
        private String secretKey;
        private String bucketName;
        private String fileName;
        private byte[] data;

        public String getAccessKey() {
            return accessKey;
        }

        public void setAccessKey(String accessKey) {
            this.accessKey = accessKey;
        }

        public String getSecretKey() {
            return secretKey;
        }

        public void setSecretKey(String secretKey) {
            this.secretKey = secretKey;
        }

        public String getBucketName() {
            return bucketName;
        }

        public void setBucketName(String bucketName) {
            this.bucketName = bucketName;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public byte[] getData() {
            return data;
        }

        public void setData(byte[] data) {
            this.data = data;
        }

        @Override
        public String toString() {
            return "Uploader{" +
                    "accessKey='" + accessKey + '\'' +
                    ", secretKey='" + secretKey + '\'' +
                    ", bucketName='" + bucketName + '\'' +
                    ", fileName='" + fileName + '\'' +
                    ", data=" + Arrays.toString(data) +
                    '}';
        }
    }
}
